"""
系统配置服务，用于管理系统级别的配置
"""
from typing import Optional, List
from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from uuid import UUID
from app.models.system_config import SystemConfig
from app.schemas.system_config import SystemConfigCreate, SystemConfigUpdate
from app.utils.security import verify_password, get_password_hash

# 系统配置键常量
ADMIN_PASSWORD_KEY = "admin_password"
DEFAULT_ADMIN_PASSWORD = "123456789"


def get_config(db: Session, config_key: str) -> Optional[SystemConfig]:
    """根据键获取配置"""
    return db.query(SystemConfig).filter(SystemConfig.config_key == config_key).first()


def get_all_configs(db: Session, skip: int = 0, limit: int = 100) -> List[SystemConfig]:
    """获取所有配置"""
    return db.query(SystemConfig).offset(skip).limit(limit).all()


def create_config(db: Session, config: SystemConfigCreate) -> SystemConfig:
    """创建新配置"""
    # 检查配置键是否已存在
    existing = get_config(db, config.config_key)
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"配置键 '{config.config_key}' 已存在"
        )
    
    db_config = SystemConfig(**config.model_dump())
    db.add(db_config)
    db.commit()
    db.refresh(db_config)
    return db_config


def update_config(db: Session, config_key: str, config_update: SystemConfigUpdate) -> SystemConfig:
    """更新配置"""
    db_config = get_config(db, config_key)
    if not db_config:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"配置键 '{config_key}' 不存在"
        )
    
    update_data = config_update.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_config, field, value)
    
    db.commit()
    db.refresh(db_config)
    return db_config


def get_or_create_admin_password(db: Session) -> str:
    """获取或创建管理员密码配置"""
    config = get_config(db, ADMIN_PASSWORD_KEY)
    
    if not config:
        # 创建默认管理员密码
        hashed_password = get_password_hash(DEFAULT_ADMIN_PASSWORD)
        config_create = SystemConfigCreate(
            config_key=ADMIN_PASSWORD_KEY,
            config_value=hashed_password,
            description="管理员登录密码"
        )
        config = create_config(db, config_create)
    
    return config.config_value


def verify_admin_password(db: Session, password: str) -> bool:
    """验证管理员密码"""
    hashed_password = get_or_create_admin_password(db)
    return verify_password(password, hashed_password)


def update_admin_password(db: Session, old_password: str, new_password: str) -> bool:
    """更新管理员密码"""
    # 验证旧密码
    if not verify_admin_password(db, old_password):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="原密码错误"
        )
    
    # 更新为新密码
    hashed_password = get_password_hash(new_password)
    config_update = SystemConfigUpdate(
        config_value=hashed_password,
        description="管理员登录密码"
    )
    
    try:
        update_config(db, ADMIN_PASSWORD_KEY, config_update)
        return True
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"密码更新失败: {str(e)}"
        )
